<?php
namespace app\index\controller;



use app\common\controller\BaseController;
use app\index\model\Avatar;
use app\index\model\ChinaCity;
use app\index\model\Ci;
use app\index\model\Users;
use PHPMailer\SendEmail;
use think\auth\Auth;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Url;

class Login extends BaseController
{



    public function login()
    {
//接数据
        $request=Request::instance();

        if($request->isPost()){
            $post=$request->post();
            if(!empty($post['kuang'])){
                $kuang=$post['kuang'];
            }
            $validate=Loader::validate('Users');
            $login=$validate->check($post);

            if(false===$login){
                $this->error($validate->getError());
            }
//                echo "<pre>";
//                print_r($post);
//                echo "</pre>";
//                exit;

                $cuo=Ci::cha($post['username']);
                if($cuo>2){
                    $this->error('登录次数超过2次,请明天再试','login');
                }

                $info=Users::login($post);
                if(null===$info) {
                    $post['cishu']=1;
                    $add=new Ci();
                    $add->add($post);
                    $this->error('账号或密码不正确...','login');
                }else {
                    Session::init();
                    Session::set('name', '1');
                    Session::set('username',$post['username']);
                    Session::set('id',$info['id']);

                    if(!empty($kuang) and $kuang==123){
                        $username=md5($post['username']);
                        $usera=substr($username,0,16);
                        $userb=substr($username,-16);
                        $id=$info['id'];

                       Db::table('app_users')->update(['id'=>$id,'md55'=>$username,'md2'=>$userb]);
                       Cookie::init();
                       Cookie::set('usera',$usera,2580000);
                       Cookie::set('username',$post['username'],2580000);
                       Cookie::set('kuang',$kuang,2580000);
                       Cookie::set('id',$id);

                    }
                    $post['cishu']=0;
                    $add=new Ci();
                    $add->add($post);
                    $this->success('登录成功', url('index/Index/index'), '', '');

                }

        }else{
            return $this->fetch();
        }
    }
    public function logink(){
        $request=Request::instance();

        $user=$request->post('username');
        Cookie::init();
        $username = Cookie::get('username');
        $md2=Cookie::get('usera');
        $id=Cookie::get('id');
        $md=Users::get($id);
        $this->assign('username', $username);

     if(!empty($md2)){
    $md55=$md2.$md['md2'];
    $info= Users::kuai($md55);
         if(null===$info) {
             $this->error('没有设置快捷登录');
         }
         $ini=Avatar::get($id);
         $img=$ini['thumb_url'];
         $n=Users::get($id);
         $na=$n['username'];

         $this->assign('img',$img);
        if($user){
            Session::init();
            Session::set('username',$na);
            Session::set('name',1);
            Session::set('id',$id);
            $post['cishu']=0;
            $add=new Ci();
            $add->add($post);
            $this->success('快捷登录成功','index/Index/index');
        }
         return $this->fetch();


        }else{
         $md55=$md2.$md['md2'];
         $info= Users::kuai($md55);
         if(null===$info) {
             $this->error('没有设置快捷登录');
         }
         return $this->fetch();
     }
    }


//    public function adduser()
//    {
//        $request = Request::instance();
//        $post = $request->post();
//        //权限
//        $uid = Session::get('id');
//        $auth = new Auth();
//        $rule = $this->request->module() . '/' . $this->request->controller() . '/' . $this->request->action();
//
//        $result = $auth->check($rule, $uid);
//
//            if ($request->isPost()) {
//
//                $validate = Loader::validate('AddUser');
//                $yan = $validate->check($post);
//                if (false === $yan) {
//                    $this->error($validate->getError());
//                }
//
//
//                $info = $this->upload_file([], 'upload', 'logo');
//
//                $data = [];
//                if (false === $info) {
//                    $data = [
//                        'status' => 0,
//                        'error' => '上传文件失败!' . $this->error,
//                        'pic_url' => '',
//                        'thumb_url' => '',
//                    ];
//                    return json($data);
//                }
//                $pic_url = str_replace(DS, '/', 'upload' . DS . $info->getSaveName());
//                $fileArr = explode('/', $pic_url);
////        return json($fileArr);
//                $thumb_url = $fileArr[0] . '/' . $fileArr[1] . '/' . 'thumb_' . $info->getFileName();
//
//                try {
//                    $water = \think\Config::get('upload_water');
//                    \think\Image::open($pic_url)->thumb(150, 150)->save($thumb_url);
//                    \think\Image::open($pic_url)->water($water)->save($pic_url);
//                    $data = [
//                        'status' => '1',
//                        'error' => '上传成功!',
//                        'pic_url' => $pic_url,
//                        'thumb_url' => $thumb_url,
//                    ];
//                    return json($data);
//                } catch (\Exception $e) {
//                    $data = [
//                        'status' => 0,
//                        'error' => '上传文件处理失败!' . $e->getMessage(),
//                        'pic_url' => '',
//                        'thumb_url' => '',
//                    ];
//                    return json($data);
//                }
//            }
////            if (!empty($post['username'])) {
////                $user = new Users();
////                $result = $user->adduser($post);
////
////                if (false === $result) {
////                    $this->error('新增失败!' . $user->getError());
////                } else {
////                    $this->success('新增成功! ID:' . $result, 'index/Index/info');
////                }
//
////        }
//else{
//            $token = $this->request->token('__token__', 'sha1');
//            $this->assign('token', $token);
//            return $this->fetch();
//        }
//    }
//--------------------------------------------------------------------------------


    public function adduser()
    {
        $request = Request::instance();
        $list=ChinaCity::getList();
        $this->assign('list',$list);


        if ($request->isPost()) {
            $post = $request->post();
            //验证器
            $validate = Loader::validate('AddUser');
            $yan = $validate->check($post);

            if (false === $yan) {
                $this->error($validate->getError());
            }


            $user = new Users();
            $result = $user->adduser($post);

            if (false === $result) {
                $this->error('新增失败!' . $user->getError());
            } else {

                $this->success('新增成功! ID:' . $result, 'index/Index/info');
            }
        }else{
            $token = $this->request->token('__token__', 'sha1');
            $this->assign('token', $token);
            $coo=Cookie::get('yzm_time');
            if(!is_null($coo)){
                $time=time()-Cookie::get('yzm_time');
                $time=120-$time;
                $this->assign('time',$time);
            }else{
                $this->assign('time',1);
            }

            return $this->fetch();
}


}






    public function san(){
        $id=Request::instance()->post('id',0);
        $list=ChinaCity::getList($id);
        return json($list);
    }



//                    //头像
//                    $file = $request->file('pic_url');
//                    if (!empty($file)){
//                    $validate = [
//                        'size' => 300 * 1024,
//                        'ext' => 'png,jpg',
//                        'type' => 'image/png,image/jpeg'
//                    ];
//                    //缩略图
//
//                    $info = $file->validate($validate)->move('static/img');
//                    $image = \think\Image::open($file);
//
//                    $tu=str_replace(DS,'',$info->getFileName());
//
//                    $image->thumb(150, 150)->save('static/img/thumb_'.$tu);
//
//
//
//                    if (false == $info) {
//                        $this->error($file->getError());
//                    } else {
//                        $name = str_replace(DS,'/',$info->getSaveName());
//                        $thumb= 'thumb_'.$tu;
//                        $post['pic_url'] = $name;
//                        $post['thumb_url'] =$thumb;
//                    }

public function edit_user(){
    Session::init();
    if(Session::get('name')!=1){
        $this->error('请先登录',url('index/Login/login','',''));
    }
    \think\Config::set('url_common_param', true);
    $request=Request::instance();
    $post=$request->post();
    $vip=\think\config::get('vip');
    $this->assign('vip2',$vip);

        $yid=$request->post('id');
        $yuantu=Avatar::get($yid);
        $yuan=$yuantu['pic_url'];
        $suolue=$yuantu['thumb_url'];

    if($request->isPost()){
        //验证
        $validate=Loader::validate('EditUser');
        $val=$validate->check($post);
        if(false===$val){
            $this->error($validate->getError());
        }


        if($request->file('pic_url')){
            $file=$request->file('pic_url');

            if($file){
                $validate = [
                    'size' => 300 * 1024,
                    'ext' => 'png,jpg',
                    'type' => 'image/png,image/jpeg'
                ];
                $info=$file->validate($validate)->move('upload');
                //缩略图
//                $image = \think\Image::open($file);


                $pic_url = str_replace(DS, '/', 'upload' . DS . $info->getSaveName());
echo "<pre>";
print_r($pic_url);
echo "</pre>";

                $fileArr = explode('/', $pic_url);
                $thumb_url = $fileArr[0] . '/' . $fileArr[1] . '/' . 'thumb_' . $info->getFileName();



                $water = \think\Config::get('upload_water');
                \think\Image::open($pic_url)->thumb(150, 150)->save($thumb_url);
                \think\Image::open($pic_url)->water($water)->save($pic_url);



//                $tu=str_replace(DS,'',$info->getFileName());
//                $image->thumb(150, 150)->save('static/upload/thumb_'.$tu);

                if(false==$info){
                    $this->error($file->getError());
                }else{

//                    $post['pic_url']=str_replace(DS,'/',$info->getSaveName());
//                    $post['thumb_url']='thumb_'.$info->getFileName();



                    $post['pic_url'] = str_replace(DS, '/', 'upload' . DS . $info->getSaveName());

                    $fileArr = explode('/', $post['pic_url']);
                    $post['thumb_url'] = $fileArr[0] . '/' . $fileArr[1] . '/' . 'thumb_' . $info->getFileName();



                    if($yuan!=''){

                        unlink($yuan);
                        unlink($suolue);

//                        unlink('static/'.$yuan);
//                        unlink('static/'.$suolue);
                    }
                }
            }

            $picObj=new Avatar();
            $res=$picObj->edit_pic($post);

            if(false===$res){
                $this->error('图片修改失败'.$picObj->getError());
            }
        }

        //存信息
        $userObj=new Users();
        $result=$userObj->edit_user($post);

        if(false===$result){
            $this->error('修改失败2'.$userObj->getError());
        }elseif(0===$result){
            $this->error('没有修改任何数据');
        }else{


            $g=input('get.');
          if(!empty($g['0'])){
              $ga=$g['0'];
          }else{
              $ga='';
          }

            $this->success('修改成功',url('index/Index/info',$ga));
        }

    }else{
        $id=$request->param('id','','');
        if(empty($id)){
            $this->error('参数异常,没接到id');
        }
        $userObj=Users::get($id);
        $pic=Avatar::get($id);
        $result=[];
        if (!is_null($userObj)) {
            $result = $userObj->toArray();
            $result['pic'] = $pic['pic_url'];
        } else {
            $this->error('参数错误');
        }
        $this->assign($result);
        return $this->fetch();

    }
}

public function edit_psw(){
    Session::init();
    if(Session::get('name')!=1){
        $this->error('请先登录',url('index/Login/login','',''));
    }
    $request=Request::instance();
    $psw=$request->post('psw');


    if($request->isPost()){

    $id=Session::get('id');
    $name=Session::get('username');

        $post = $request->post();
        $validate=Loader::validate('Editpsw');
        $val=$validate->check($post);
        if(false===$val){
            $this->error($validate->getError());
        }
        //验证原密码
        $post['id']=$id;
        $post['username']=$name;
        $info=Users::loginn($post);
        if(null===$info) {
            $this->error('原密码不正确');
        }

        $pswObj=new Users();

        $request=$pswObj->editpsw($post);
        if (false === $request) {
            $this->error('修改失败' . $pswObj->getError());
        } elseif (0 === $request) {
            $this->error('没有修改任何数据');
        } else {

            $this->success('修改成功', 'Index/info');
        }
    }
    $token = $this->request->token('__token__', 'sha1');
    $this->assign('token', $token);
    return $this->fetch();
}

    public function repsw(){
        echo 123;

        $this->fetch();
    }



    public function chongpsw(){
        $request=Request::instance();
        if($request->isPost()){
            //验证用户名和邮箱
            $username=$request->post('username','','trim');
            $email=$request->post('email','','trim');
            $ret=Users::checkeMail($username,$email);
            if(null===$ret){
            $this->error('账号或邮件不匹配','login');
            }
            //发送电子邮件
            $email=$ret->email;
            $ret = \app\index\model\Users::setTime($ret->id,'reset');

            if(empty($ret)){
                $this->error('找回密码邮件发送失败！！！','forget');
            }

            $code  = Users::getCode($ret->id,'reset');
            if(false === $code){
                $this->error('找回密码邮件发送失败！！','forget');
            }

            $link = Url::build('reset',['s'=>$code],'',true);


//            $rt = SendEmail::SendEmail('邮件重置',$link,$email);
//            $toemail='static7@qq.com';
//            $name='static7';
            $subject='重置密码';

           $rt=send_mail($email,$username,$subject,$link);

            if ($rt) {
                $this->success('邮件发送成功', 'index/Login/login');
            } else {
                $this->error('邮件发送失败', 'index/Login/login');
            }
        }

       return $this->fetch();
    }

public function reset(){
    $request=Request::instance();

    if($request->isPost()){
        $post = $request->post();

        $validate=Loader::validate('Resetpsw');
        $val=$validate->check($post);
        if(false===$val){
            $this->error($validate->getError());
        }
        $userId = Session::pull('tmpUserId');
        $userObj = new Users();
        $data = [
            'id'  => $userId,
            'password'  => $post['password'],
        ];
        $result = $userObj->editpsw($data);

        if(false === $result){
            $this->error('密码修改失败！','login');
        }else{
            $this->success('密码修改成功！请登录！','login');
        }

    }else{
        $code = $request->param('s','','trim,htmlspecialchars,strip_tags');
        // 对加密字符串进行校验
        $userObj = Users::checkCode($code,'reset');

        if(false === $userObj){
            $this->error('链接已经失效!!！','login');
        }
        // 取出reset_time
        $reset_time = intval($userObj->getData('reset_time'));
        $now = intval(time());
        // 重设reset_time
        $ret = \app\index\model\Users::setTime($userObj->id,'reset');
        if(empty($ret)){
            $this->error('链接已经失效','login');
        }
        //链接过期
        if(($now - $reset_time) >= 60){
            $this->error('链接已经过期,期限60秒！！','login');
        }
        Session::init();
        Session::set('tmpUserId',$userObj->id);
        $token = $this->request->token('__token__', 'sha1');
        $this->assign('token', $token);
        return $this->fetch();
    }
}










}